<template>
    <div class="app-container" ref="mainContyainers">
        <el-row :gutter="0">
            <!--专病数据-->
            <el-form class="formBox formBox1 searchForm" :model="queryParams" ref="queryForm" size="small" :inline="true"
                v-show="showSearch" label-width="68px">
                <el-form-item label="选择医院">
                    <department :isHospital="true" :isdepat="true" @refreshData="refreshData" deptWidth="180px"
                        ref="department" :isUserAll="true">
                    </department>
                </el-form-item>
                <el-form-item label="医生姓名" prop="nickName">
                    <el-select v-model="queryParams.nickName" clearable filterable placeholder="医生姓名" style="width: 180px">
                        <el-option v-for="dict in userListArray" :key="dict.userId" :label="dict.nickName"
                            :value="dict.nickName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择时间">
                    <el-date-picker v-model="dateRange" style="width: 200px;margin-right:10px;"
                        :picker-options="pickerOptions" value-format="yyyy-MM-dd" type="daterange" size="mini"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery"
                        :clearable="false"></el-date-picker>
                </el-form-item>
               
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                    <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    <el-button icon="el-icon-printer" size="mini" type="success" @click="handleExport">导出</el-button>
                </el-form-item>
            </el-form>
            <div class="formBox searchForm" ref="statisticalTable" style="margin-bottom:0px!important;">

                <el-table border v-loading="loading" :data="tableLists" show-summary :summary-method="getSummaries"
                    id="out-table" ref="table" :height="statisticalTableH">
                    <!--                <el-table-column type="selection" width="50" align="center" />-->
                    <el-table-column label="序号" align="center" type="index" width="50" fixed>
                        <template slot-scope="scope">
                            <span>{{ getIndex(scope.$index) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="员工账号" align="center" prop="userName" :show-overflow-tooltip="true" width="100"
                        fixed />
                    <el-table-column label="员工姓名" align="center" prop="nickName" :show-overflow-tooltip="true" width="140"
                        fixed />
                    <el-table-column label="登记人数（人次）" align="center" prop="vsitCount" :show-overflow-tooltip="true"
                        width="80" />
                    <el-table-column label="采集照片数(张)" align="center" prop="photoCount" :show-overflow-tooltip="true"
                        width="100" />
                    <el-table-column label="咨询人数（人次）" align="center" prop="consultationCount" :show-overflow-tooltip="true"
                        width="80">
                        <!-- <template slot-scope="scope">
                            <dict-tag :options="dict.type.sys_manage_diseases" :value="scope.row.diseaseIds" />
                        </template> -->
                    </el-table-column>
                    <el-table-column label="诊断人数" align="center">
                        <el-table-column align="center" prop="doctorCount" label="初诊人数（人次）" width="120">
                            <!-- <template slot-scope="scope">
                            <span>{{getdoctorCountFirst(scope.row.doctorReviewCount,scope.row.doctorCount)}}</span>
                        </template>  -->
                        </el-table-column>
                        <el-table-column prop="doctorReviewCount" align="center" label="复诊人数（人次）" width="120">
                        </el-table-column>
                        <el-table-column align="center" prop="doctorAllCount" label="总人数（人次）" width="120">
                        </el-table-column>
                    </el-table-column>

                    <el-table-column label="治疗人数（人次）" align="center" prop="treatmentCount" :show-overflow-tooltip="true"
                        width="100">
                        <!-- <template slot-scope="scope">
                    <dict-tag :options="dict.type.sys_manage_diseases" :value="scope.row.diseaseIds" />
                </template> -->
                    </el-table-column>


                    <el-table-column label="电话随访" align="center" prop="status" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>-</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="开单收入（元）" align="center" prop="doctorPrice" :show-overflow-tooltip="true"
                        width="150">

                        <el-table-column prop="doctorPrice" align="center" label="总收入（元）" width="120">
                            <template slot-scope="scope">
                                <div v-if="scope.row.doctorPrice" style="color:red;font-size:16px">{{ scope.row.doctorPrice
                                }}
                                </div>
                                <div v-else>-</div>
                            </template>
                        </el-table-column>
                        <el-table-column align="center" prop="doctorPrice" label="治疗费收入（元）" width="120">
                            <template slot-scope="scope">
                                <div v-if="scope.row.doctorTreatmentPrice" style="color:red;font-size:16px">{{
                                    scope.row.doctorTreatmentPrice }}
                                </div>
                                <div v-else>-</div>
                            </template>
                        </el-table-column>

                    </el-table-column>
                    <el-table-column label="已治疗收入（元）" align="center" prop="treatmentPrice" :show-overflow-tooltip="true"
                        width="150">
                        <template slot-scope="scope">
                            <div v-if="scope.row.treatmentPrice" style="color:red;font-size:16px">{{
                                scope.row.treatmentPrice }}</div>
                            <div v-else>-</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="退费" align="center" prop="status" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="投诉" align="center" prop="status" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="表扬" align="center" prop="status" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>-</span>
                        </template>
                    </el-table-column>

                    <!-- <el-table-column label="创建时间" align="center" prop="status" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime) }}</span>
                        </template>
                    </el-table-column> -->


                </el-table>
                <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
            </div>

        </el-row>
    </div>
</template>

<script>
//引入安装的依赖
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
import XLSXD from "xlsx-style";
// statisticsTreatmentuserByTime
import { statisticsTreatmentuserByTime } from "@/api/system/specialCom";
import {
    listUser,
} from "@/api/system/user";
import department from "@/views/components/department/index.vue";
export default {
    name: "doctorSum",
    dicts: [

    ],
    components: { department },
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now() - 8.64e6;  //如果没有后面的-8.64e6就是不可以选择今天的
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '前天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
                        const end = date;
                        const start = date;
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近六个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近1年',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            tableLists: [],
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 日期范围
            dateRange: [],
            // 表单参数
            // form: {},
            form: {

            },
            pageNum: 1,
            pageSize: 10,
            // 查询参数
            queryParams: {
                // pageNum: 1,
                // pageSize: 10,
                hospitalId: '',
                deptId: '',
                nickName:''
            },
            statisticalTableH: undefined,
            userListArray: []
        };
    },
    watch: {},
    computed: {
        defaultTime: function () {//默认当月1号 到 现在
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month = month > 9 ? month : "0" + month;
            day = day < 10 ? "0" + day : day;
            let day0 = '01';
            let today = year + "-" + month + "-" + day;
            let firtsDay = year + "-" + month + "-" + day0;
            return [firtsDay, today];
        },
    },
    async created() {

    },
    mounted() {
        this.dateRange = this.defaultTime
        this.changeHeight()

    },
    updated() {
        this.$nextTick(() => {

            this.$refs.table.doLayout()
        })
    },
    methods: {
        /** 查询用户列表 */
        getUserList() {
            let params = {
                pageNum: 1,
                pageSize: 9999,
                deptId: this.queryParams.deptId ? this.queryParams.deptId : this.queryParams.hospitalId,
            }
            listUser(params).then(
                (response) => {
                    this.userListArray = response.rows;
                }
            );
        },
        changeHeight() {
            if (this.$refs.statisticalTable) {
                const statisticalTableObj = this.$refs.statisticalTable.getBoundingClientRect();
                let h = statisticalTableObj.top + 30
                this.statisticalTableH = 'calc(100vh - ' + h + 'px)'
            } else {
                this.statisticalTableH = '500px'
            }
        },
        getSummaries(param) {
            let that = this
            const { columns, data } = param;
            const sums = [];
            //  console.log(columns)
            // console.log(data)
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                if (index === 1 || index === 2) {
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return Math.floor(prev * 100) / 100 + Math.floor(curr * 100) / 100;
                        } else {
                            return Math.floor(prev * 100) / 100;
                        }
                    }, 0);
                    sums[index] += '';
                } else {
                    sums[index] = 'N/A';
                }


            });
            return sums;
        },
        refreshData(data) {
            console.log(data)
            if (data.hospitalId) {
                this.queryParams.hospitalId = data.hospitalId
                this.queryParams.deptId = data.deptId

            } else {
                this.queryParams.hospitalId = '100'
            }
            this.getUserList()
            this.getList()

        },
        getdoctorCountFirst(rewCount, count) {
            if (count) {
                if (rewCount) {
                    return Number(count) + Number(rewCount)
                }
            }
        },
        // 真实序号计算（计算分页影响）
        getIndex(index) {
            return (this.pageNum - 1) * this.pageNum + index + 1;
        },
        /** 查询设备列表 */
        getList() {
            let that = this
            that.loading = true;
            let params = {
                startTime: that.dateRange[0],
                endTime: that.dateRange[1],
                ...that.queryParams
            }
            statisticsTreatmentuserByTime(params).then((response) => {
                if (response.code == 200) {
                    let data = response.data;

                    data.forEach(function (ele) {
                        ele.doctorAllCount = that.getdoctorCountFirst(ele.doctorReviewCount, ele.doctorCount)
                    })
                    this.tableLists = data

                }
                that.loading = false;
            });
        },
        // 取消按钮
        cancel() {

        },
        // 表单重置
        reset() {

        },
        handleExport() {
            let tables = document.getElementById('out-table').cloneNode(true) // 重点
            if (tables.querySelector(".el-table__fixed")) {
                tables.removeChild(tables.querySelector(".el-table__fixed")) // 重点
            }
            let wb = XLSX.utils.table_to_book(tables, { sheet: '医生工作统计' })
            this.setExlStyle(wb['Sheets']['医生工作统计'])
            //合并单元格边框补齐
            this.addRangeBorder(wb['Sheets']['医生工作统计']['!merges'], wb['Sheets']['医生工作统计'])
            var ws = XLSXD.write(wb, {
                type: "buffer"
            });
            try {
                FileSaver.saveAs(
                    new Blob([ws], { type: "application/octet-stream" }),
                    `医生工作统计_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, ws);
            }
            return ws;
            // this.download(
            //     "system/statistics/export/userByTime",
            //     {
            //         ...this.addDateRange(this.queryParams, this.dateRange)

            //     },
            //     `医生工作统计_${this.dateRange[0]}~${this.dateRange[1]}.xlsx`
            // );
        },
        setExlStyle(data) {
            let borderAll = {//单元格外侧框线
                top: {
                    style: 'thin',
                },
                bottom: {
                    style: 'thin'
                },
                left: {
                    style: 'thin'
                },
                right: {
                    style: 'thin'
                }
            };
            data['!cols'] = [];
            for (let key in data) {
                if (data[key] instanceof Object) {
                    data[key].s = {
                        border: borderAll,
                        alignment: {
                            horizontal: 'center',//水平居中对齐
                            vertical: 'center'
                        },
                        font: {
                            sz: 11
                        },
                        bold: true,
                        numFmt: 0
                    }
                    data['!cols'].push({ wpx: 120 });
                }
            }
            return data;
        },
        addRangeBorder(range, ws) {
            let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
            range.forEach(item => {
                let startRowNumber = Number(item.s.c),
                    endRowNumber = Number(item.e.c);
                for (let i = startRowNumber; i <= endRowNumber; i++) {
                    for (let j = Number(item.s.r) + 1; j <= Number(item.e.r); j++) {
                        ws[`${arr[i]}${j + 1}`] = { s: { border: { top: { style: 'thin' }, left: { style: 'thin' }, bottom: { style: 'thin' }, right: { style: 'thin' } } } };
                    }
                }

            })
            return ws;

        },
        /** 搜索按钮操作 */
        handleQuery() {
            // this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            if (this.$refs.department) {
                this.$refs.department.reset()
            }
        },
    },
};
</script>
<style scoped lang="scss">
::v-deep .statisticalTable .el-table .cell {
    font-size: 12px;
}</style>
